<?php
require_once('./includes/headers.inc.php');
require_once('./top.php');

$error = FALSE;
$user_id = $_GET['id'];
$is_current_user = ($user_id == $_SESSION['user']['id']);
$user_data = $userMgr->get($user_id, $_SESSION['user']['id']);
$lastDate = '';
$lastUserId = 0;
$lastLocationId = 0;
if(!$user_data['id']) {
    header('Location: /notfound.php');
    exit();
}

if($_POST) {
    //if follow button was pushed, follow viewed user
    if(isset($_POST['follow'])) {
        $ret = $userMgr->follow($_SESSION['user']['id'], $_POST['id']);
        if($ret) {
            $error = $msgMgr->get('friend-follow-success');
            $user_data = $userMgr->get($user_id, $_SESSION['user']['id']);
        } else {
            $error = $msgMgr->get('friend-follow-error');
        }
    //if unfollow button was pushed, unfollow viewed user
    } elseif(isset($_POST['unfollow'])) {
        $ret = $userMgr->unfollow($_SESSION['user']['id'], $_POST['id']);
        if($ret) {
            $error = $msgMgr->get('friend-unfollow-success');
            $user_data = $userMgr->get($user_id, $_SESSION['user']['id']);
        } else {
            $error = $msgMgr->get('friend-unfollow-error');
        }
    }
} else {
    if(isset($_SESSION['msg']) && $_SESSION['msg']) {
        $error = $_SESSION['msg'];
        unset($_SESSION['msg']);
    }
}

$canBeFriended = ($user_data['friend_id'] == 0 && $user_data['active'] && $user_data['id'] != $_SESSION['user']['id']);
if(!$user_data['is_follower'] && $user_id != $_SESSION['user']['id']) {
    //user is not you and is not following you, hide email address for privacy
    $user_data['username'] = $langMgr->get('text_email_hidden');
}

if($canBeFriended) {
    $friend_info = '<input type="submit" name="follow" value="' . $langMgr->get('Follow this user') . '">';
} else {
    if($user_data['friend_id']) {
        $friend_info = '<p>' . $langMgr->get('text_user_following') . ' <input type="submit" name="unfollow" value="' . $langMgr->get('text_user_unfollow') . '"></p>';
    } elseif($user_data['id'] == $_SESSION['user']['id']) {
        $friend_info = $langMgr->get('text_isyou');
    } else {
        $friend_info = '';
    }
}

$user_info = $userMgr->getUserRouteStats($user_id);

$locations = $locationMgr->getAll();
$completion_stats = array();
foreach($locations as $row) {
   $stats = $userMgr->getUserCompletionStats($user_id, $row['id']);
   if($stats) {
      $completion_stats[] = '<h2>' . $row['name'] . '</h2><img src="stats_user_completion.php?id=' . $user_id . '&location=' . $row['id'] . '">';
   }
}

$routes = $userMgr->getUserFeed($user_id, 30, TRUE);
$latest_routes = array('<ul id="feed" class="viewuser">');
foreach($routes as $row) {
    switch($row['completed']) {
        case -1:
            $completed = '<span class="notcompleted">&nbsp;</span>';
            break;
        case 0:
            $completed = '<span class="completed">&nbsp;</span>';
            break;
        default:
            $text = $langMgr->get('text_completed_with_x_blocks', false, array('num' => $row['completed']));
            $completed = '<span class="blockcompleted" title="' . $text . '">&nbsp;</span>';
            break;
    }
    $own = ($row['user_id'] == $_SESSION['user']['id'] ? TRUE : FALSE);
    $date = date('d-m-Y', strtotime($row['timestamp']));
    if($date != $lastDate || $row['location_id'] != $lastLocationId) {
       $firstItem = TRUE;
       $header = '<li class="user ' . ($own ? 'own' : '') . '"><a href="/viewlocation.php?id=' . $row['location_id'] . '">' . $row['location'] . '</a>' .  ($own ? '<span class="delete"><a href="/deletecheckin.php?id=' . $row['id'] . '">&#x2718;</a></span>' : '') . '</li>';
    } else {
       $firstItem = FALSE;
       $header = '';
    }
    $item = array(
        $header,
        '<li class="location">',
        '<ul>',
            '<li class="date">' . $date . '</li>',
            '<li class="route">' . $completed . '<span class="colour ' . $row['colour'] . '"><a href="/viewroute.php?id=' . $row['route_id'] . '">' . $row['colour'] . ' ' . $row['difficulty'] . ($row['is_short'] ? ' (short)' : '') . '</a></span> ' . ($row['unicode'] ? '<img class="routetype ' . $row['route_type'] . '" src="/img/pixel.png"> ' : '') . '<i>' . $row['route_name'] . '</i></li>',
            ($row['comment'] ? '<li class="comment">' . $row['comment'] . '</li>' : ''),
            '</ul></li>'
    );
    $latest_routes[] = implode("\n", $item);
    $lastDate = $date;
    $lastLocationId = $row['location_id'];
}
$latest_routes[] = '</ul>';

$replaces = array(
    'id'                        => $user_data['id'],
    'name'                      => $user_data['name'],
    'username'                  => $user_data['username'],
    //'friend_count'              => $user_data['friend_count'],
    'registered'                => date('d-m-Y', strtotime($user_data['registered'])),
    'active'                    => ($user_data['active'] ? '' : '<li>' . $langMgr->get('text_user_inactive') . '</li>'),
    'change_info'               => ($is_current_user ? '<a href="/account.php">' . $langMgr->get('text_edit_myaccount') . '</a>' : ''),
    'user_list'                 => (in_array($_SESSION['user']['id'], $admin_users) ? '<p><a href="/viewallusers.php">' . $langMgr->get('text_admin_viewusers') . '</a></p>' : ''),
    'friend_info'               => $friend_info,
    //'route_count'               => $user_info['route_count'],
    //'count'                     => $user_info['count'],
    //'complete_count'            => $user_info['completed'],
    //'complete_perc'             => ($user_info['count'] ? round(100 * $user_info['completed'] / $user_info['count']) . '%' : '0%'),
    //'block_count'               => $user_info['blocked'],
    //'block_perc'                => ($user_info['completed'] ? round(100 * $user_info['blocked'] / $user_info['completed']) . '%' : '0%'),
    'completion_stats'          => implode("\n", $completion_stats),
    'latest_checkins'           => implode("\n", $latest_routes),
    'error'                     => $msgMgr->formatMsg($error),
);
$lang = array(
    'header_userinfo'           => $langMgr->get('header_userinfo'),
    'text_registeredon'         => $langMgr->get('text_registeredon'),
    'text_followingxfriends'    => $langMgr->get('text_followingxfriends', false, array('friend_count' => $user_data['friend_count'])),
    'header_climbingstats'      => $langMgr->get('header_climbingstats'),
    'text_scaledxroutes'        => $langMgr->get('text_scaledxroutes', false, array('route_count' => $user_info['route_count'], 'count' => $user_info['count'])),
    'text_completedxtimes'      => $langMgr->get('text_completedxtimes', false, array('complete_count' => $user_info['completed'], 'complete_perc' => ($user_info['count'] ? round(100 * $user_info['completed'] / $user_info['count']) . '%' : '0%'))),
    'text_blockedxtimes'        => $langMgr->get('text_blockedxtimes', false, array('complete_count' => $user_info['completed'], 'block_count' => $user_info['blocked'], 'block_perc' => ($user_info['completed'] ? round(100 * $user_info['blocked'] / $user_info['completed']) . '%' : '0%'))),
    'header_weekstats'          => $langMgr->get('header_weekstats'),
    'text_weekstats_intro'      => $langMgr->get('text_weekstats_intro'),
    'text_lastweeks'            => $langMgr->get('text_lastweeks'),
    'header_diffrange'          => $langMgr->get('header_diffrange'),
    'text_diffrange_intro'      => $langMgr->get('text_diffrange_intro'),
    'header_locationcompletion' => $langMgr->get('header_locationcompletion'),
    'text_locationcompletion_intro' => $langMgr->get('text_locationcompletion_intro'),
);

$templateMgr->loadContent(basename(__FILE__, '.php'), array_merge($replaces, $lang));
?>
